package com.jnxg.smartcommunity.manager;


import android.app.Activity;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


public class ActivityManager {

	private static List<Activity> activityStack;
	private static ActivityManager instance;

	public static ActivityManager getInstance() {
			if (instance == null) {
				instance = new ActivityManager();
			}
		return instance;
	}
	public ActivityManager() {
		activityStack = new ArrayList<Activity>();
	}
	public void popActivity() {
		if (activityStack.size() > 0) {
			Activity activity = activityStack.remove(activityStack.size() - 1);
			if (activity != null) {
				activity.finish();
				activity = null;
			}
		}
	}
	public void popActivity(Activity activity) {
		if (activity != null) {
			activity.finish();
			activityStack.remove(activity);
			activity = null;
		}
	}
	public Activity currentActivity() {
		if (activityStack.size() > 0) {
			Activity activity = activityStack.remove(activityStack.size() - 1);
			return activity;
		}
		return null;
	}
	public void pushActivity(Activity activity) {
		activityStack.add(activity);
	}
	public void popToActivity(Class<?> cls) {
		while (true) {
			Activity activity = null;
			if (activityStack.size() > 0) {
				activity = activityStack.get(activityStack.size() - 1);
			}
			if (activity == null) {
				break;
			}
			if (activity.getClass().equals(cls)) {
				break;
			}
			popActivity(activity);
		}
	}
	public boolean hasActivity(Class<?> cls) {
		Iterator<Activity> iter = activityStack.iterator();
		while (iter.hasNext()) {
			if (iter.next().getClass().equals(cls))
				return true;
		}
		return false;
	}
	public void popPassActivity(Class<?> cls) {
		while (true) {
			Activity activity = null;
			if (activityStack.size() > 0) {
				activity = activityStack.get(activityStack.size() - 1);
			}
			if (activity == null) {
				break;
			}
			if (activity.getClass().equals(cls)) {
				popActivity(activity);
				break;
			}
			popActivity(activity);
		}
	}

	public void saveActivity(Class<?> cls) {
		int i = 0;
		while (activityStack.size() > i) {
			Activity activity = activityStack.get(activityStack.size() - i - 1);
			if (activity.getClass().equals(cls) && i == 0) {
				i = 1;
			} else {
				popActivity(activity);
			}
		}
	}

	public static void finish() {
		while (activityStack.size() > 0) {
			Activity activity = activityStack.remove(activityStack.size() - 1);
			if (activity != null) {
				activity.finish();
				activity = null;
			}
		}
	}

	private static long time;
//
//	public  static void exit() {
//		if (System.currentTimeMillis() - time > 1.5 * 1000L) {
//			time = System.currentTimeMillis();
//			return;
//		}
//		finish();
//	}
}
